package com.example.mallorder.controller;

import com.example.mallorder.controller.vo.OrderConfirmVO;
import com.example.mallorder.controller.vo.OrderResponseVO;
import com.example.mallorder.controller.vo.OrderSubmitVO;
import com.example.mallorder.service.OrderService;
import com.exception.NoStockExecption;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

/**
 * @author guanglin.ma
 * @date 2024-01-08 19:20
 */
@Controller
public class ConfirmController {

    @Autowired
    private OrderService orderService;

    @GetMapping("/toTrade")
    public String toTrade(Model model) {
        // TODO 查询订单确认页需要的信息
        OrderConfirmVO confirmVo = orderService.confirmOrder();
        model.addAttribute("confirmVO", confirmVo);
        return "confirm";
    }

    @GetMapping("/confirm.html")
    public String getConfirm(Model model) {
        OrderConfirmVO orderConfirmVO = orderService.confirmOrder();
        model.addAttribute("confirmVO", orderConfirmVO);
        return "confirm";
    }

    @PostMapping("/orderSubmit")
    public String orderSubmit(OrderSubmitVO orderSubmitVO, Model model, RedirectAttributes redirectAttributes) {

        Integer code = 0;
        OrderResponseVO responseVO = null;
        try {
            responseVO = orderService.orderService(orderSubmitVO);
            code = responseVO.getCode();
        } catch (NoStockExecption e) {
            code = 2;
        }

        if (code == 0) {
            model.addAttribute("orderResponseVO", responseVO);
            // 表示下单操作成功
            return "pay";
        } else {
            System.out.println("code=" + code);
            String msg = "订单失败";
            if (code == 1) {
                msg = msg + ":重复提交";
            } else if (code == 2) {
                msg = msg + ":锁定库存失败";
            }
            //redirectAttributes.addAttribute("msg",msg);
            redirectAttributes.addFlashAttribute("msg", msg);
            // 表示下单操作失败
            return "redirect:http://order.mg.com/toTrade";
        }
    }

    @GetMapping("/detail.html")
    public String getDetail(Model model) {
        return "detail";
    }

    @GetMapping("/order.html")
    public String getOrder(Model model) {
        return "order";
    }

    @GetMapping("/pay.html")
    public String getPay(Model model) {
        return "pay";
    }

}
